import React, { Fragment } from 'react'
import Listitem from './Listitem'
// import axios from 'axios'


class Todolist extends React.Component {
    constructor() {
        super()
        this.state = {
            inputValue: 'hello',
            list: ['我爱react', '111']
        }

    }

    change() {
        this.setState({
            inputValue: this.input.value
        })
    }
    add() {

        if (this.state.inputValue === '') {
            alert("请输入内容")
            return
        }
        this.setState(() =>
            ({
                list: [...this.state.list, this.state.inputValue],
                inputValue: ''
            })
        )
    }

    delete(index) {
        let list = [...this.state.list]
        list.splice(index, 1)
        this.setState({
            list: list
        })

    }
    handleKeydown(e) {
        if (e.keyCode === 13) {
            this.add();
        }
    }

    render() {
        return (
            <Fragment>
                <Listitem index={this.state} content={this.state.inputValue}></Listitem>
                <input className="form-control"
                    style={{ "width": "200px", "display": "inline" }}
                    type="text"
                    value={this.state.inputValue}
                    onChange={this.change.bind(this)}
                    onKeyDown={this.handleKeydown.bind(this)}
                    ref={(input) => this.input = input}
                />
                <input type="button" onClick={this.add.bind(this)}
                    className="btn btn-info" value="提交" />
                <ol>
                    {
                        this.state.list.map((item, index) => {
                            return <li title="点击删除" onClick={this.delete.bind(this, index)}
                                key={index}>{item}</li>
                        })
                    }
                </ol>
            </Fragment>
        )
    }

    componentDidMount() {
        console.log("componentDidMount：组件被挂载到页面之后自动执行")
        // axios.get('/students').then((res) => {
        //     console.log(res.data)
        //     this.setState(() => ({
        //         list: [...res.data]
        //     }))

        // }).catch(() => { alert('error') })
    }
}

export default Todolist